#!/usr/bin/python
# -*- coding: utf-8 -*-

#为方便以后移植，参数中的 key 一律为字符串格式
import logging
from google.appengine.ext import db
from google.appengine.api import memcache 
from google.appengine.api import users

import googledatabase
import getcounter
import commonfunction
import databasefunction

LIKE_ID_COUNT_NAME = 'LikeIDCount'


#===================================== 喜欢的 =============================================

#获得用户最多的收藏记录集
#返回： 结果集
def GetHotLikeRecord(PageSize):
    Query = db.GqlQuery('SELECT * FROM CLikeTable ORDER BY UserNumber DESC')
    return Query.fetch(PageSize)


#获得一个收藏记录
def GetOneLikeItem(SourceUrl, LoginName = ''):
    if 1 > len(SourceUrl):
        return None

#    logging.debug("------------ GetOneTableItem: TableName = %s, ItemKeyStr = %s" % (TableName, ItemKeyStr))
    Query = db.GqlQuery( 'SELECT * FROM CLikeTable WHERE SourceUrl = :1', SourceUrl )
    if 0 < len(LoginName):
        Query = db.GqlQuery( 'SELECT * FROM CMyLikeTable WHERE SourceUrl = :1 AND LoginName = :2', SourceUrl, LoginName )

    Results = Query.fetch(1)
    if Results:
        return Results[0]
    else:
        return None



#分页、逆时获得一个用户的收藏内容
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneUserLikeRecord(UserLoginName, PageSize, TimeDelta, TagDate = ''):
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM CMyLikeTable WHERE LoginName = :1 AND Date > :2 ORDER BY Date',
                             UserLoginName, commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        logging.debug( "--------------------- LikeRecord 1: len(Results) = %d" % (len(Results)) )
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- LikeRecord: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )
            
    #计算下一页起始ID
    Query = db.GqlQuery( 'SELECT * FROM CMyLikeTable WHERE LoginName = :1 ORDER BY Date DESC', UserLoginName )
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM CMyLikeTable WHERE LoginName = :1 AND Date <= :2 ORDER BY Date DESC',
                             UserLoginName, commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- LikeRecord 2: len(Results) = %d" % (len(Results)) )
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正时间和用户昵称
    for Item in Results:
        Item.LoginName = commonfunction.GetOneUserNickName(Item.LoginName)
        if '' == Item.LoginName:
            Item.LoginName = commonfunction.GetEmptyNickName(TimeDelta)
                
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag


#分页、顺时获得一个收藏的评论内容
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneLikeCommentOnRecord(SourceUrl, PageSize, TimeDelta, TagDate = ''):
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( "SELECT * FROM CMyLikeTable WHERE HaveCommentOn = True AND SourceUrl = :1 AND Date < :2 ORDER BY Date DESC",
                             SourceUrl, commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        logging.debug( "--------------------- LikeRecord 1: len(Results) = %d" % (len(Results)) )
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- LikeRecord: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )
            
    #计算下一页起始ID
    Query = db.GqlQuery( "SELECT * FROM CMyLikeTable WHERE HaveCommentOn = True AND SourceUrl = :1 ORDER BY Date", SourceUrl )
    if 0 < len(TagDate):
        Query = db.GqlQuery( "SELECT * FROM CMyLikeTable WHERE HaveCommentOn = True AND SourceUrl = :1 AND Date >= :2 ORDER BY Date",
                             SourceUrl, commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- LikeRecord 2: len(Results) = %d" % (len(Results)) )
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正时间和用户昵称
    for Item in Results:
        Item.LoginName = commonfunction.GetOneUserNickName(Item.LoginName)
        if '' == Item.LoginName:
            Item.LoginName = commonfunction.GetEmptyNickName(TimeDelta)
                
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag

#添加一个收藏
def AddOneLike(Title, SourceUrl, Type, CommentOn):
    if 1 > len(Title) or 1 > len(SourceUrl):
        return

    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        LoginName = os.environ["REMOTE_ADDR"]
    
    MyAlreadyItem = GetOneLikeItem(SourceUrl, LoginName)
    if MyAlreadyItem:
        return
    
    SysAlreadyItem = GetOneLikeItem(SourceUrl)
    if SysAlreadyItem:
        db.run_in_transaction(databasefunction.AddOnePropertyCount, SysAlreadyItem.key(), 'UserNumber', 1) 
    else:
        SysAlreadyItem = googledatabase.CLikeTable()
        SysAlreadyItem.ID = getcounter.GetAutoIncrementCount(LIKE_ID_COUNT_NAME)
        SysAlreadyItem.Title = Title
        SysAlreadyItem.SourceUrl = SourceUrl
        SysAlreadyItem.Type = Type
        SysAlreadyItem.UserNumber = 1
        SysAlreadyItem.put()
    
        #清理缓存区数据
        memcache.delete('CLikeTable_New')
        memcache.delete('CLikeTable_PrePage')
        memcache.delete('CLikeTable_NextPage')


    if 0 < len(LoginName):
        MyAlreadyItem = googledatabase.CMyLikeTable()
        MyAlreadyItem.Title = Title
        MyAlreadyItem.SourceUrl = SourceUrl
        MyAlreadyItem.Type = Type
        MyAlreadyItem.LoginName = LoginName
        if 0 < len(CommentOn):
            MyAlreadyItem.HaveCommentOn = True
            MyAlreadyItem.CommentOn = CommentOn
        MyAlreadyItem.put()
    


def DeleteSelfOneLike(DeleteUrl):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return

    Query = db.GqlQuery("SELECT * FROM CMyLikeTable WHERE SourceUrl = :1", DeleteUrl)
    Results = Query.fetch(1) 
    db.delete(Results)

    Query = db.GqlQuery("SELECT * FROM CLikeTable WHERE SourceUrl = :1", DeleteUrl)
    Item = Query.get()
    if Item:
        db.run_in_transaction(databasefunction.AddOnePropertyCount, Item.key(), 'UserNumber', -1) 
    


def DeleteSelfOneLikeByKey(DeleteKeyStr):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return

    DeleteUrl = ''
    Query = db.GqlQuery( "SELECT * FROM CMyLikeTable WHERE __key__ = :1", db.Key(DeleteKeyStr) )
    Results = Query.fetch(1)
    if Results:
        DeleteUrl = Results[0].SourceUrl
    db.delete(Results)

    if DeleteUrl and 0 < len(DeleteUrl):
        Query = db.GqlQuery("SELECT * FROM CLikeTable WHERE SourceUrl = :1", DeleteUrl)
        Item = Query.get()
        if Item:
            db.run_in_transaction(databasefunction.AddOnePropertyCount, Item.key(), 'UserNumber', -1) 


    
def DeleteSysOneLike(DeleteUrl):
    if False == commonfunction.UserIsAdmin():
        return

    Query = db.GqlQuery("SELECT * FROM CMyLikeTable WHERE SourceUrl = :1", DeleteUrl)
    Results = Query.fetch(1000)
    db.delete(Results)

    Query = db.GqlQuery("SELECT * FROM CLikeTable WHERE SourceUrl = :1", DeleteUrl)
    Results = Query.fetch(1)

    DeleteLikeKeyStr = ''
    if Results:
        DeleteLikeKeyStr = str(Results[0].key())

    db.delete(Results)

    if TheItemInMemcacheRecord('CLikeTable_New', DeleteLikeKeyStr):
        #清理缓存区数据
        memcache.delete('CLikeTable_New')
        memcache.delete('CLikeTable_PrePage')
        memcache.delete('CLikeTable_NextPage')



